{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "内容相同的文件有：\n",
      "哈希值: ed42cc3415b6554407fdc736c2f58daf\n",
      "  - zy - 副本 (2).xlsx\n",
      "  - zy - 副本 (4).xlsx\n",
      "  - zy - 副本 (5).xlsx\n",
      "  - zy - 副本 (6).xlsx\n",
      "  - zy - 副本 (7).xlsx\n",
      "  - zy.xlsx\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import hashlib\n",
    "from collections import defaultdict\n",
    "\n",
    "# 定义文件夹路径\n",
    "folder_path = r'C:\\Users\\lenovo\\Desktop\\python作业\\作业7'\n",
    "\n",
    "# 函数：计算文件的MD5哈希值\n",
    "def calculate_md5(file_path):\n",
    "    hash_md5 = hashlib.md5()\n",
    "    with open(file_path, \"rb\") as f:\n",
    "        for chunk in iter(lambda: f.read(4096), b\"\"):\n",
    "            hash_md5.update(chunk)\n",
    "    return hash_md5.hexdigest()\n",
    "\n",
    "# 存储文件哈希值和文件名的字典\n",
    "file_hashes = defaultdict(list)\n",
    "\n",
    "# 遍历指定目录下的所有文件\n",
    "for root, _, files in os.walk(folder_path):\n",
    "    for file in files:\n",
    "        file_path = os.path.join(root, file)\n",
    "        file_hash = calculate_md5(file_path)\n",
    "        file_hashes[file_hash].append(file_path)\n",
    "\n",
    "# 找出内容相同的文件\n",
    "duplicate_files = {hash_value: paths for hash_value, paths in file_hashes.items() if len(paths) > 1}\n",
    "\n",
    "# 显示内容相同的文件名\n",
    "if duplicate_files:\n",
    "    print(\"内容相同的文件有：\")\n",
    "    for hash_value, paths in duplicate_files.items():\n",
    "        print(f\"哈希值: {hash_value}\")\n",
    "        for path in paths:\n",
    "            print(f\"  - {os.path.basename(path)}\")\n",
    "else:\n",
    "    print(\"没有找到内容相同的文件\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
